/**
 * Javascript plugins for our board.
 *
 * @author Nick Goris
 * @version $id$
 */

var marketcrashed = false;
var previous_marketcrash_status = false;
var apply_marketcrash_sound = false;
var play_pricechanged_sound = false;

 (function($) {
    // get
//the following setting come from index.html
//    page = 1;
//    lines = 11;
//    no_pages = false;

	
    parseBeers();
    setInterval(parseBeers, 5000);

    function ajaxSetup() {
        $.ajaxSetup({
            cache: false
        });
    }

    function parseBeers() {
        // The returned data: Schiphol departures of today.
        // The kind people of Schiphol return this in JSON, so it will be easy to parse.
        //var url = "departures.php";
        var url = "../beerlist.php";

        ajaxSetup();

        $.ajax({
            type: "GET",
            dataType: 'json',
            url: url,
            error: function(response) {
                alert(response);
            },
            success: function(response) {
                var table = $('#beers > tbody:last'); // our table
                var beers = response; // our response
                var j = 0; // our custom counter
                var startno = lines * (page - 1);
                var endno = startno + lines;
				var beerimage = '';

                if (endno > beers.length) {
                    endno = beers.length;
                    if (!no_pages)
						page = 0;
                }
                for (var i = startno; i < endno; i += 1) {
                    var beer = beers[i]; // our beer
                    // check if object exists
                    var row = $('#beer' + j, table);
                    var crashed = '';
					
					//add an icon for crashed items
                    if (beer.crashed) {
                        crashed = "<img src='img/attention.gif' id='attention' name='attention' />";
						if (!marketcrashed) {
							marketcrashed = true;
						} 
                    }
					apply_marketcrash_sound |= beer.apply_marketcrash_sound;
					play_pricechanged_sound |= beer.play_pricechanged_sound;
					
                    if (row && row.length > 0) {
						beerimage = '<img src="../img/' + beer.image + '" id="productimage" />';
						//var image='';

						$('td.procimage', row).html(beerimage);
                        $('td.name', row).html(beer.description + crashed);

                        var openprice = beer.openprice.toFixed(2);
                        if (beer.openprice === 0 || beer.stockavailable <= 0) {
                            openprice = '-.--';
                        }
                        $('td.openprice', row).html(openprice);

                        var cell_currprice = $('td.currprice', row);
                        var currprice = beer.currprice.toFixed(2);
                        if (beer.stockavailable <= 0) {
                            currprice = '-.--';
                        }
                        cell_currprice.html(currprice);
                        //change color with change cell
						if (currprice != '-.--') {
							if (beer.change < 0) {
								cell_currprice[0].className = 'currprice red';
							} else if (beer.change > 0) {
								cell_currprice[0].className = 'currprice green';
							} else {
								cell_currprice[0].className = 'currprice';
							}
						} else {
							cell_currprice[0].className = 'currprice';
						}

                        var cell_change = $('td.change', row);
                        var change = beer.change.toFixed(2);
                        if (beer.change === 0 || beer.stockavailable <= 0) {
                            change = '-.--';
                        }
                        cell_change.html(change);
						if (currprice != '-.--') {
							if (beer.change < 0) {
								cell_change[0].className = 'change red';
							} else if (beer.change > 0) {
								cell_change[0].className = 'change green';
							} else {
								cell_change[0].className = 'change';
							}
						} else {
							cell_change[0].className = 'change';
						}

                        $('td.stockavailable', row).html(beer.stockavailable);
                    } else {
                        var rowClass = ($('#beers > tbody:last tr:last').hasClass('even')) ? 'odd' : 'even';
                        var str = '<tr id="beer' + j + '" class="' + rowClass + '">';
                        var crashed = '';
						
						beerimage = '<img src="../img/' + beer.image + '" id="productimage" />';
						//var image='';

						str += createCell('procimage', beerimage, '');
                        //add an icon for crashed items
                        if (beer.crashed) {
                            crashed = "<img src='img/attention.gif' id='attention' name='attention' />";
                        }

                        str += createCell('name', beer.description + crashed, '');


                        var openprice = beer.openprice.toFixed(2);
                        if (beer.openprice === 0 || beer.stockavailable <= 0) {
                            openprice = '-.--';
                        }
                        str += createCell('openprice', openprice, '');

                        var color = '';
                        var change = beer.change.toFixed(2);
                        var currprice = beer.currprice.toFixed(2);

                        if (beer.change === 0) {
                            change = '-.--';
                        } else if (beer.change < 0) {
                            color = 'red';
                        } else
                            color = 'green';

                        if (beer.stockavailable <= 0) {
							currprice = '-.--';
                            change = '-.--';
                            color = '';
                        }
                        str += createCell('currprice', currprice, color);
                        str += createCell('change', change, color);
                        str += createCell('stockavailable', beer.stockavailable, '');

                        str += '</tr>';
                        table.append(str);

                    }

                    j += 1; // add one
                    //if (j > 20) break; // stop after a 100
                }
                //for last page may not has all rows, so, clear the rest rows
                if (j < lines) {
                    for (var n = j; n < lines; n += 1) {
                        row = $('#beer' + n, table);
                        if (row && row.length > 0) {
							$('td.procimage', row).html('');
							$('td.name', row).html('');
							$('td.openprice', row).html('');
							var cell_currprice = $('td.currprice', row);
							cell_currprice.html('');
							cell_currprice[0].className = 'currprice';
							var cell_change = $('td.change', row);
							cell_change.html('');
							cell_change[0].className = 'change';
							$('td.stockavailable', row).html('');
                        } else {
							var rowClass = ($('#beers > tbody:last tr:last').hasClass('even')) ? 'odd' : 'even';
							var str = '<tr id="beer' + n + '" class="' + rowClass + '">';
							
							str += createCell('procimage', '', '');
							//add an icon for crashed items
							str += createCell('name', '', '');
							str += createCell('openprice', '', '');
							str += createCell('currprice', '', '');
							str += createCell('change', '', '');
							str += createCell('stockavailable', '', '');

							str += '</tr>';
							table.append(str);
						}
                    }
                }
                
                if (!no_pages) {
                    page += 1;
                }
				
				if (apply_marketcrash_sound) {
					if ((marketcrashed == true) && (previous_marketcrash_status == false)) {
						jBeep('sound/marketcrashstart.wav');
					}
					if ((marketcrashed == false) && (previous_marketcrash_status == true)) {
						jBeep('sound/marketcrashstop.wav');
					}
				}
				
				if (play_pricechanged_sound) {
					jBeep('sound/pricechanged.wav');
				}
				previous_marketcrash_status = marketcrashed;
				marketcrashed = false;
				apply_marketcrash_sound = false;
				play_pricechanged_sound = false;
            }
        });
    }


    function createCell(name, data, color) {
		name = name + ' ' + color;
        return '<td class="' + name + '">' + data + '</td>';
    }



})(window.jQuery);

window.log = function() {
    log.history = log.history || [];
    log.history.push(arguments);
    if (this.console) {
        console.log(Array.prototype.slice.call(arguments));
    }
};

(function(doc) {
    var write = doc.write;
    doc.write = function(q) {
        log('document.write(): ', arguments);
        if (/docwriteregexwhitelist/.test(q))
            write.apply(doc, arguments);
    };
})(document);
